//
//  ZTRegisterViewController.m
//  ZTuo_QuantivitiTrasaction
//
//  Created by chu on 2018/11/27.
//  Copyright © 2018 chu. All rights reserved.
//

#import "ZTRegisterViewController.h"
#import "ZTResourceViewController.h"

@interface ZTRegisterViewController ()<UITextFieldDelegate>
{
    NSInteger _countDown;
    NSTimer *_timer;
}

@property (weak, nonatomic) IBOutlet UIButton *registButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewMarginTopConstraint;

@end

@implementation ZTRegisterViewController

- (void)dealloc{
    [_timer invalidate];
    _timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _countDown = 60;
    self.navigationItem.title=@"注册";
    
    self.passwordTF.delegate = self;
    
    self.registButton.layer.masksToBounds = YES;
    self.registButton.layer.cornerRadius = self.registButton.frame.size.height / 2;
}

- (IBAction)getCode:(UIButton *)sender {
    [self.view endEditing:YES];
    //先判断手机号
    if (self.phoneTF.text.length <= 0) {
        [self.view makeToast:@"请输入您的手机号" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    [self checkPhoneIsRegist];
}

- (void)checkPhoneIsRegist{
    
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"checkPhone"];
    NSDictionary *param = @{@"phone":self.phoneTF.text};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"验证手机号是否注册 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
            self.codeBtn.enabled = YES;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [self getVerify];
            }else{
                self.codeBtn.enabled = YES;
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (void)getVerify{
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"code"];
    NSDictionary *param = @{@"phone":self.phoneTF.text};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"验证码 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
            self.codeBtn.enabled = YES;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                self->_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];

            }else{
                self.codeBtn.enabled = YES;
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

#pragma mark - PrivateMethod
- (void)onTimer{
    if (_countDown > 0) {
        [self.codeBtn setTitle:[NSString stringWithFormat:@"%ld秒重新获取", (long)_countDown] forState:UIControlStateNormal];
        _countDown--;
    }else{
        _countDown = 60;
        [_timer invalidate];
        _timer = nil;
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.codeBtn.enabled = YES;
    }
}

- (IBAction)registAction:(UIButton *)sender {
    [self goRegister];
}

- (IBAction)login:(UIButton *)sender {
    BOOL haveLoginVC = NO;
    UIViewController *loginVC = nil;
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:NSClassFromString(@"LoginViewController")]) {
            haveLoginVC = YES;
            loginVC = vc;
            break;
        }
    }
    if (haveLoginVC) {
        [[AppDelegate sharedAppDelegate] popToViewController:loginVC];
    }else{
        LoginViewController *login = [[LoginViewController alloc] init];
        [[AppDelegate sharedAppDelegate] pushViewController:login];
    }
    
}

- (void)goRegister{
    if ([NSString stringIsNull:self.phoneTF.text]) {
        [self.view makeToast:@"请输入手机号码" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if ([NSString stringIsNull:self.codeTF.text]) {
        [self.view makeToast:@"请输入验证码" duration:1.5 position:CSToastPositionCenter];
        return;
    }

    if ([NSString stringIsNull:self.passwordTF.text]) {
        [self.view makeToast:@"请输入密码" duration:1.5 position:CSToastPositionCenter];
        return;
    }

    if (self.passwordTF.text.length <= 5) {
        [self.view makeToast:@"密码最短6位" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    [EasyShowLodingView showLodingText:Loading];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"regist"];
    NSDictionary *param = @{@"mobile":self.phoneTF.text, @"captcha":self.codeTF.text, @"password":self.passwordTF.text};
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"注册 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                
                [[AppDelegate sharedAppDelegate] popViewController];
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];

            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.passwordTF) {
        NSString *resultStr = [self.passwordTF.text stringByReplacingCharactersInRange:range withString:string];
        if (resultStr.length == 16) {
            return NO;
        }
    }
    return YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //设置导航栏透明
    [self.navigationController.navigationBar setTranslucent:true];
    //把背景设为空
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //处理导航栏有条线的问题
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[NSFontAttributeName] = [UIFont boldSystemFontOfSize:17];
    attributes[NSForegroundColorAttributeName] = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(popAction)];
}

- (void)popAction{
    [[AppDelegate sharedAppDelegate] popViewController];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setTranslucent:NO];
    
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[NSFontAttributeName] = [UIFont boldSystemFontOfSize:17];
    attributes[NSForegroundColorAttributeName] = [UIColor blackColor];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
}


- (void)updateViewConstraints{
    [super updateViewConstraints];
    self.backViewHeightConstraint.constant = CGRectGetMaxY(self.registButton.frame) + 70;
    self.scrollViewMarginTopConstraint.constant = - Height_NavBar;

}

@end
